package com.hemaapp.yjnh.chat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Video.VideoColumns;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.Loader.OnLoadCompleteListener;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.uu.utils.uuFileUtils;
import com.buihha.audiorecorder.Mp3Recorder;
import com.buihha.audiorecorder.TimeThread;
import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.chat.ChatClient;
import com.hemaapp.hm_FrameWork.chat.ChatConfig;
import com.hemaapp.hm_FrameWork.chat.ChatDBClient;
import com.hemaapp.hm_FrameWork.chat.ChatFresh;
import com.hemaapp.hm_FrameWork.chat.ChatFresh.ChatFreshListener;
import com.hemaapp.hm_FrameWork.chat.ChatMessage;
import com.hemaapp.hm_FrameWork.chat.ChatMessageHelper;
import com.hemaapp.hm_FrameWork.chat.ChatSendListener;
import com.hemaapp.hm_FrameWork.chat.FirPagCount;
import com.hemaapp.hm_FrameWork.chat.FirPagDBClient;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog.OnButtonListener;
import com.hemaapp.hm_FrameWork.emoji.ParseEmojiMsgUtil;
import com.hemaapp.hm_FrameWork.emoji.SelectFaceHelper;
import com.hemaapp.hm_FrameWork.emoji.SelectFaceHelper.OnFaceOprateListener;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.view.ChatLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.ClientDetails;
import com.hemaapp.yjnh.bean.FileUploadResult;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.PermissionUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import vn.tungdx.mediapicker.MediaItem;
import vn.tungdx.mediapicker.MediaOptions;
import vn.tungdx.mediapicker.activities.MediaPickerActivity;
import vn.tungdx.mediapicker.utils.MediaUtils;
import xtom.frame.fileload.XtomFileDownLoader;
import xtom.frame.media.XtomVoicePlayer;
import xtom.frame.media.XtomVoicePlayer.XtomVoicePlayListener;
import xtom.frame.util.XtomBaseUtil;
import xtom.frame.util.XtomFileUtil;
import xtom.frame.util.XtomImageUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomListView.XtomSizeChangedListener;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

/**
 * 私聊页面(注意不要忘了assets文件夹下emoji.xml文件)
 */
public class ChatPrivateActivity extends BaseActivity implements ChatSendListener, ChatFreshListener {
    private static final int TOTALSECOND = 90;// 录音的最长时长
    private static final int REQUEST_VIDEO = 0x201;// 获取手机内的视频
    private static final int REQUEST_VIDEO_CAPTURE = 0x202;// 拍摄视频
    private static final int REQUEST_ALBUM = 0x203;// 获取手机内的照片
    private static final int REQUEST_CAMERA_PERMISSION = 300;//相机请求权限

    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.listview)
    XtomListView listview;
    @Bind(R.id.layout_refresh)
    ChatLoadmoreLayout layoutRefresh;
    @Bind(R.id.editor)
    EditText editor;
    @Bind(R.id.layout_add)
    LinearLayout layoutAdd;
    @Bind(R.id.face_viewpager)
    ViewPager faceViewpager;
    @Bind(R.id.msg_face_index_view)
    LinearLayout msgFaceIndexView;
    @Bind(R.id.tv_audio_during)
    TextView tvAudioDuring;
    @Bind(R.id.iv_audio)
    ImageView ivAudio;
    @Bind(R.id.iv_delete)
    ImageView ivDelete;
    @Bind(R.id.rootView)
    LinearLayout rootView;
    @Bind(R.id.layout_audio)
    LinearLayout layoutAudio;
    @Bind(R.id.layout_face)
    LinearLayout layoutFace;
    @Bind(R.id.btn_send)
    Button btnSend;

    private String to_client_id;//对方的id
    private String to_nickname;//对方的昵称
    private String to_avatar;//对方的头像

    private String cameraPath;// 拍照时图片保存路径

    //语音消息
    private String audioSecond;//录制的声音时长
    private String audioPath;
    private Mp3Recorder mRecorder;//录制声音的插件
    private XtomVoicePlayer voicePlayer;//语音播放器

    // 表情相关
    private SelectFaceHelper mFaceHelper;

    private ChatClient mClient;
    private ArrayList<ChatMessage> chatMessages = new ArrayList<ChatMessage>();
    private ChatMessageHelper messageHelper;
    private ChatPrivateAdapter mAdapter;
    private User user;
    private ClientDetails details;//聊天对象的信息

    private List<MediaItem> mImageSelectedList;
    private List<MediaItem> mVideoSelectedList;//已选择的视频
    private boolean takePhotoPending = false;
    private boolean takeVideoPending = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        mClient = new ChatClient(to_client_id, "1", user.getNickname(),
                user.getAvatar(), this, getApplicationContext());
        messageHelper = ChatMessageHelper.getSINInstance(
                getApplicationContext(), ChatConfig.LOGIN_CID, to_client_id);
        messageHelper.setHelperListener(new MessageHelperListener());
        ChatFresh.addChatFreshListener(this);
        messageHelper.getNextPage();
    }

    @Override
    public void onResume() {
//        chatFresh();
        super.onResume();
        //判断录音权限
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            final HemaButtonDialog dialog = new HemaButtonDialog(mContext);
            dialog.setText("请在权限管理中打开录音权限");
            dialog.setRightButtonText("设置");
            dialog.setButtonListener(new OnButtonListener() {
                @Override
                public void onLeftButtonClick(HemaButtonDialog hemaButtonDialog) {
                    dialog.cancel();
                    finish();
                }

                @Override
                public void onRightButtonClick(HemaButtonDialog hemaButtonDialog) {
                    dialog.cancel();
                    PermissionUtils.gotoMiuiPermission(mContext);
                }
            });
        } else {
            if (mRecorder == null)
                mRecorder = new Mp3Recorder(mContext, recordHandler);//初始化录音
        }
    }

    @Override
    public void chatFresh() {
        messageHelper.getNewMessages();
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        to_client_id = mIntent.getStringExtra("to_client_id");
        to_nickname = mIntent.getStringExtra("to_nickname");
        to_avatar = mIntent.getStringExtra("to_avatar");
        if (isNull(to_client_id)) {
            showTextDialog("数据获取异常");
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    finish();
                }
            }, 1500);
        } else if (isNull(to_nickname) || isNull(to_avatar)) {
            getNetWorker().clientGet(user.getToken(), to_client_id);
        }
    }

    @Override
    protected void setListener() {
        titleText.setText(to_nickname);
        titleRightBtn.setText("清空");
        editor.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(TextUtils.isEmpty(s.toString())) {
                    btnSend.setEnabled(false);
                }else
                    btnSend.setEnabled(true);
            }
        });
        listview.setXtomSizeChangedListener(new SizeChangedListener());
        layoutRefresh.setOnStartListener(new OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                messageHelper.getNextPage();
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {

            }
        });
        layoutRefresh.setLoadmoreable(false);
        //语音消息
        ivAudio.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        if (isNull(audioPath)) {
                            startAudioRecord();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (!isNull(audioPath) && !mRecorder.isRecording()) {
                            if (voicePlayer == null || !voicePlayer.isPlaying())
                                startPlay();
                            else
                                stopPlay(false);
                            break;
                        } else {
                            finishAudioRecord();
                        }
                        break;
                    case MotionEvent.ACTION_CANCEL:// 当手指移动到view外面，会cancel
                        finishAudioRecord();
                        break;
                }
                return true;
            }
        });
    }

    @OnClick({R.id.title_left_btn, R.id.title_right_btn, R.id.btn_add, R.id.btn_emoji,
            R.id.btn_send, R.id.btn_camera, R.id.btn_album, R.id.btn_audio, R.id.btn_video,
            R.id.btn_record_video, R.id.iv_delete, R.id.editor})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_btn:
                HemaButtonDialog dialog = new HemaButtonDialog(mContext);
                dialog.setText("您确定要清空吗？");
                dialog.setRightButtonText("清空");
                dialog.setButtonListener(new OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        ChatDBClient client = ChatDBClient.get(mContext);
                        client.delete(to_client_id);
                        chatMessages.clear();
                        if (mAdapter != null)
                            mAdapter.notifyDataSetChanged();
                        // 删除首页计数(若项目需求删除聊天记录的同时不需删除首页计数注释下面代码即可)
                        FirPagDBClient fpClient = FirPagDBClient.get(mContext);
                        FirPagCount count = new FirPagCount(null, null, null, to_client_id,
                                null, null, null, null, null, null, null, null, null);
                        fpClient.delete(count);
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
            case R.id.btn_add:
                if (layoutFace.getVisibility() == View.VISIBLE)
                    layoutFace.setVisibility(View.GONE);
                if (layoutAudio.getVisibility() == View.VISIBLE)
                    layoutAudio.setVisibility(View.GONE);
                if (layoutAdd.getVisibility() == View.VISIBLE) {
                    mInputMethodManager.showSoftInput(editor, 0);
                    layoutAdd.setVisibility(View.GONE);
                } else {
                    mInputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),
                            0);
                    layoutAdd.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.btn_emoji:
                if (null == mFaceHelper) {
                    mFaceHelper = new SelectFaceHelper(ChatPrivateActivity.this,
                            layoutFace);
                    mFaceHelper.setFaceOpreateListener(mOnFaceOprateListener);
                }

                if (layoutAdd.getVisibility() == View.VISIBLE)
                    layoutAdd.setVisibility(View.GONE);
                if (layoutFace.getVisibility() == View.VISIBLE) {
                    layoutFace.setVisibility(View.GONE);
                    mInputMethodManager.showSoftInput(editor, 0);
                } else {
                    // 隐藏键盘
                    mInputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),
                            0);
                    layoutAdd.setVisibility(View.GONE);
                    layoutFace.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.btn_send:
                String textContent = editor.getText().toString();
                if (!isNull(textContent)) {
                    String content = ParseEmojiMsgUtil.convertToMsg(editor.getText(),
                            mContext);
                    sendText(content);
                    editor.setText(null);
                } else if (!isNull(audioPath)) {
                    if (isNull(audioPath))
                        log_i("不用发送录音");
                    else {
                        User user = getApplicationContext().getUser();
                        getNetWorker().fileUpload(user.getToken(), "8", "0",
                                audioSecond, "0", "无", audioPath);
                        resetAudio();
                    }
                }
                break;
            case R.id.btn_camera:
                String imageName = XtomBaseUtil.getFileName() + ".jpg";
                Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                String imageDir = XtomFileUtil.getTempFileDir(mContext);
                cameraPath = imageDir + imageName;
                File file = new File(imageDir);
                if (!file.exists())
                    file.mkdir();
                // 设置图片保存路径
                File out = new File(file, imageName);
                Uri uri = Uri.fromFile(out);
                it.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(it, 1);
                break;
            case R.id.btn_album:
//                Intent itAlbum = new Intent(Intent.ACTION_PICK,
//                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(itAlbum, 0);
                MediaOptions.Builder builder = new MediaOptions.Builder();
                MediaOptions options = null;
                options = builder.canSelectMultiPhoto(false)
                        .setMediaListSelected(mImageSelectedList)
                        .setCanTakePhoto(false)
                        .build();
                MediaPickerActivity.open(mContext, REQUEST_ALBUM, options);
                break;
            case R.id.btn_audio:
                if (layoutAdd.getVisibility() == View.VISIBLE)
                    layoutAdd.setVisibility(View.GONE);
                layoutAudio.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_video:
                MediaOptions.Builder builderVideo = new MediaOptions.Builder();
                MediaOptions optionsVideo = null;
                optionsVideo = builderVideo.selectVideo()
                        .canSelectMultiVideo(false)
                        .setCanTakeVideo(false)
                        .build();
                MediaPickerActivity.open(mContext, REQUEST_VIDEO, optionsVideo);
                break;
            case R.id.btn_record_video:
                performTakeVideoRequest();
                break;
            case R.id.iv_delete:
                resetAudio();
                break;
            case R.id.editor:
                layoutAdd.setVisibility(View.GONE);
                layoutFace.setVisibility(View.GONE);
                layoutAudio.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    protected boolean onKeyBack() {
        if (layoutFace.getVisibility() == View.VISIBLE) {
            layoutFace.setVisibility(View.GONE);
        } else if (layoutAudio.getVisibility() == View.VISIBLE) {
            layoutAudio.setVisibility(View.GONE);
        } else {
            if (layoutAdd.getVisibility() == View.VISIBLE) {
                layoutAdd.setVisibility(View.GONE);
            } else {
                finish();
            }
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;

        switch (requestCode) {
            case REQUEST_ALBUM:// 相册选择图片
                mImageSelectedList = MediaPickerActivity
                        .getMediaItemSelected(data);
                if (mImageSelectedList != null && mImageSelectedList.size() > 0) {
                    new CompressPicTask().execute(mImageSelectedList.get(0).getPathOrigin(mContext));
                }
                break;
            case 1:// 拍照
                new CompressPicTask().execute(cameraPath);
                break;
            case 2:// 本地选择视频
                albumVideo(data);
                break;
            case 3:// 录制视频
                recordVideo(data);
                break;
            case REQUEST_VIDEO:// 本地选择视频
                mVideoSelectedList = MediaPickerActivity
                        .getMediaItemSelected(data);
                if (mVideoSelectedList != null) {
                    for (MediaItem mediaItem : mVideoSelectedList) {
                        sendVideo(mediaItem.getPathOrigin(mContext));
                    }
                } else {
                    Toast.makeText(this, "视频选择失败", Toast.LENGTH_SHORT).show();
                }
                break;
            case REQUEST_VIDEO_CAPTURE://录制视频
                checkVideo(data.getData());
                break;
        }
    }

    // 录制视频
    private void recordVideo(Intent data) {
        Uri uri = data.getData();
        Cursor cursor = this.getContentResolver().query(uri, null, null, null,
                null);
        if (cursor != null && cursor.moveToNext()) {
            final String videoPath = cursor.getString(cursor
                    .getColumnIndex(VideoColumns.DATA));
            cursor.close();
            log_i("videoPath=" + videoPath);
            sendVideo(videoPath);
        }
    }

    // 相册选择视频
    private void albumVideo(Intent data) {
        if (data == null)
            return;
        Uri selectedImageUri = data.getData();
        // 获取视频路径
        String[] proj = {MediaStore.Images.Media.DATA};
        final CursorLoader loader = new CursorLoader(mContext);
        loader.setUri(selectedImageUri);
        loader.setProjection(proj);
        loader.registerListener(0, new OnLoadCompleteListener<Cursor>() {

            @Override
            public void onLoadComplete(Loader<Cursor> arg0, Cursor cursor) {
                int columnIndex = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                final String videoPath = cursor.getString(columnIndex);
                log_i("videoPath=" + videoPath);
                sendVideo(videoPath);
                loader.stopLoading();
                cursor.close();
            }
        });
        loader.startLoading();
    }

    private void sendVideo(final String videoPath) {
        File file = new File(videoPath);
        if (!file.exists()) {
            XtomToastUtil.showShortToast(mContext, "视频文件不存在");
            return;
        }

        long k = file.length() / 1024;
        double m = (double) k / (double) 1024;
        if (m > 5) {
            XtomToastUtil.showShortToast(mContext, "您选择的视频太大了哦，亲");
            return;
        }

        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(videoPath);
            mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

                @Override
                public void onPrepared(MediaPlayer mp) {
                    User user = getApplicationContext().getUser();
                    Integer s = mp.getDuration() / 1000;
                    if (s % 1000 != 0)
                        s++;
                    getNetWorker().fileUpload(user.getToken(), "9", "0",
                            s.toString(), "0", "无", videoPath);
                    mp.release();
                }
            });
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            //
        }
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FILE_UPLOAD:
                showProgressDialog("正在发送发件");
                break;
            case CHATPUSH_ADD:
                // nothing
                break;
            case CLIENT_GET:
                showProgressDialog("请稍候");
                break;
            default:
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FILE_UPLOAD:
            case CLIENT_GET:
                cancelProgressDialog();
                break;
            case CHATPUSH_ADD:
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FILE_UPLOAD:
                @SuppressWarnings("unchecked")
                HemaArrayResult<FileUploadResult> fResult = (HemaArrayResult<FileUploadResult>) baseResult;
                FileUploadResult uploadResult = fResult.getObjects().get(0);
                String item1 = uploadResult.getItem1();
                String item2 = uploadResult.getItem2();
                String keytype = netTask.getParams().get("keytype");
                User user = getApplicationContext().getUser();
//			String deptName = user.getDeptname();
//			if (isNull(deptName))
//				deptName = "";
                if ("7".equals(keytype)) {// 图片
                    mClient.sendImage_siliao(item1, item2, "", to_client_id,
                            to_avatar, to_nickname, "");
                } else if ("8".equals(keytype)) {// 语音
                    mClient.sendVoice_siliao(item1, "", item2, to_client_id,
                            to_avatar, to_nickname, "");
                } else if ("9".equals(keytype)) {// 视频
                    mClient.sendVedio_siliao(item1, "", item2, to_client_id,
                            to_avatar, to_nickname, "");
                }
                break;
            case CHATPUSH_ADD:
                log_i("聊天推送发送成功");
                break;
            case CLIENT_GET:
                HemaArrayResult<ClientDetails> uResult = (HemaArrayResult<ClientDetails>) baseResult;
                details = uResult.getObjects().get(0);
                to_avatar = details.getAvatar();
                to_nickname = details.getNickname();
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FILE_UPLOAD:
                XtomToastUtil.showShortToast(mContext, "文件发送失败");
                break;
            case CHATPUSH_ADD:
                log_i("聊天推送发送失败");
                break;
            case CLIENT_GET:
                showTextDialog("数据获取异常");
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1500);
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FILE_UPLOAD:
                XtomToastUtil.showShortToast(mContext, "文件发送失败");
                break;
            case CHATPUSH_ADD:
                log_i("聊天推送发送失败");
                break;
            case CLIENT_GET:
                showTextDialog("数据获取异常");
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1500);
                break;
            default:
                break;
        }
    }

    // 发送普通text聊天消息
    public void sendText(String str) {
        mClient.sendText_siliao(str, to_client_id, to_avatar, to_nickname,
                "");
    }

    // 重新发送聊天消息
    public void sendAgain(ChatMessage cMessage) {
        mClient.sendMsg(cMessage);
    }


    @Override
    public void noStart(ChatMessage cMessage) {
        showSendState(cMessage);
    }

    @Override
    public void noConnect(ChatMessage cMessage) {
        XtomToastUtil.showShortToast(mContext, "发送失败，无法连接服务器");
        showSendState(cMessage);
    }

    @Override
    public void sucess(ChatMessage cMessage) {
        showSendState(cMessage);
        chatPush(cMessage);
    }

    // 发送聊天推送
    private void chatPush(ChatMessage cMessage) {
        String msgtype = cMessage.getdxpacktype();// 1：文本 2：图片 3：音频 4：视频
        String content = cMessage.getStanza();
        if (content.length() > 50)
            content = content.substring(0, 50);
        String group_id = cMessage.getdxgroupid();
        String recv_id = cMessage.getTojid();
        String group_name = cMessage.getdxgroupname();
        String token = getApplicationContext().getUser().getToken();
        getNetWorker().chatpushAdd(token, msgtype, content, group_id, recv_id,
                group_name);
    }

    @Override
    public void failed(ChatMessage cMessage) {
        showSendState(cMessage);
    }

    /**
     * 显示发送状态
     *
     * @param cMessage
     */
    private void showSendState(ChatMessage cMessage) {
        messageHelper.updateMessage(cMessage);
    }

    @Override
    public void onPause() {
        // messageHelper.clearcount(); //清空未读计数
        super.onPause();
    }

    @Override
    public void onStop() {
        ChatFresh.removeChatFreshListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        ChatFresh.removeChatFreshListener(this);
        super.onDestroy();
        releaseVoicePlayer();
    }

    // 释放语音播放器资源
    private void releaseVoicePlayer() {
        if (mAdapter == null)
            return;
        XtomVoicePlayer voicePlayer = mAdapter.getVoicePlayer();
        if (voicePlayer != null)
            voicePlayer.release();
    }

    @Override
    public void finish() {
        // mDbClient.updateSend(to_client_id, "0");// 将发送失败消息置为失败
        // mDbClient.updateRead(to_client_id, "0");// 将未读消息置为已读
        messageHelper.clearcount(); // 清空未读计数
        super.finish();
    }

    private void refreshUI() {
        if (mAdapter == null) {
            mAdapter = new ChatPrivateAdapter(this, rootView, chatMessages,
                    listview);
            mAdapter.setEmptyString("没有聊天记录");
            listview.setAdapter(mAdapter);
            listview.setSelection(mAdapter.getCount());
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    private class MessageHelperListener implements
            ChatMessageHelper.HelperListener {

        @Override
        public void onNextPage(ArrayList<ChatMessage> messages) {
            layoutRefresh.stopRefresh();
            addAll(messages, true);
            refreshUI();
            if (messages == null)
                layoutRefresh.setRefreshable(false);
            else {
                int size = messages.size();
                listview.setSelection(size);
            }

        }

        @Override
        public void onNewMessages(ArrayList<ChatMessage> messages) {
            boolean isBottom = isNeedToBottom();
            addAll(messages, false);
            refreshUI();
            if (isBottom)
                toBottom();
        }

        @Override
        public void onUpdate(ChatMessage message) {
            boolean isBottom = isNeedToBottom();
            addOrUpdate(message, false);
            refreshUI();
            if (isBottom) {
                listview.removeCallbacks(bottomRunable);
                listview.postDelayed(bottomRunable, 300);
            }
        }

        private Runnable bottomRunable = new Runnable() {

            @Override
            public void run() {
                toBottom();
            }
        };

        private boolean isNeedToBottom() {
            if (mAdapter == null)
                return true;
            int last = listview.getLastVisiblePosition();
            int count = mAdapter.getCount() - 1;
            return last == count;
        }

        // 将listview滑动至底部
        private void toBottom() {
            listview.setSelection(mAdapter.getCount());
        }

        private void addAll(ArrayList<ChatMessage> messages, boolean isTop) {
            if (messages == null)
                return;

            int size = messages.size();
            if (isTop)// 如果是向顶端添加,反序遍历
                for (int i = size - 1; i >= 0; i--) {
                    ChatMessage cm = messages.get(i);
                    addOrUpdate(cm, isTop);
                }
            else
                // 反之,正序遍历
                for (ChatMessage cm : messages) {
                    addOrUpdate(cm, isTop);
                }
        }

        private void addOrUpdate(ChatMessage message, boolean isTop) {
            if (message == null)
                return;
            ChatMessage cm = contains(message);
            if (cm == null) {
                if (isTop)
                    chatMessages.add(0, message);
                else
                    chatMessages.add(message);
            } else {
                int index = chatMessages.indexOf(cm);
                chatMessages.remove(index);
                message.setVoicePlaying(cm.isVoicePlaying());
                chatMessages.add(index, message);
            }
        }

        private ChatMessage contains(ChatMessage message) {
            for (ChatMessage cm : chatMessages) {
                String packid = message.getdxpackid();
                if (cm.getdxpackid().equals(packid))
                    return cm;
            }

            return null;
        }
    }

    // listview布局改变监听
    private class SizeChangedListener implements XtomSizeChangedListener {
        @Override
        public void onSizeChanged(XtomListView view, int w, int h, int oldw,
                                  int oldh) {
            ListAdapter a = view.getAdapter();
            if (a != null && oldh > h)
                view.setSelection(a.getCount());
        }
    }

    /**
     * 压缩图片
     */
    private class CompressPicTask extends AsyncTask<String, Void, Integer> {
        String compressPath;

        @Override
        protected Integer doInBackground(String... params) {
            try {
                String path = params[0];
                String savedir = XtomFileUtil.getTempFileDir(mContext);
                compressPath = XtomImageUtil.compressPictureWithSaveDir(path,
                        BaseConfig.IMAGE_HEIGHT, BaseConfig.IMAGE_WIDTH,
                        BaseConfig.IMAGE_QUALITY, savedir, mContext);
                return 0;
            } catch (Exception e) {
                return 1;
            }
        }

        @Override
        protected void onPreExecute() {
            showProgressDialog("正在压缩图片");
        }

        @Override
        protected void onPostExecute(Integer result) {
            cancelProgressDialog();
            switch (result) {
                case 0:
                    User user = getApplicationContext().getUser();
                    getNetWorker().fileUpload(user.getToken(), "7", "0", "0", "0",
                            "无", compressPath);
                    break;
                case 1:
                    showTextDialog("图片压缩失败");
                    break;
            }
        }
    }

    OnFaceOprateListener mOnFaceOprateListener = new OnFaceOprateListener() {
        @Override
        public void onFaceSelected(SpannableString spanEmojiStr) {
            if (null != spanEmojiStr) {
                editor.append(spanEmojiStr);
            }
        }

        @Override
        public void onFaceDeleted() {
            int selection = editor.getSelectionStart();
            String text = editor.getText().toString();
            if (selection > 0) {
                String text2 = text.substring(selection - 1);
                if ("]".equals(text2)) {
                    int start = text.lastIndexOf("[");
                    int end = selection;
                    editor.getText().delete(start, end);
                    return;
                }
                editor.getText().delete(selection - 1, selection);
            }
        }

    };

    /**
     * 删除录音，重新初始化
     */
    private void resetAudio() {
        audioPath = null;
        ivDelete.setVisibility(View.INVISIBLE);
        audioSecond = "";
        btnSend.setEnabled(false);
        tvAudioDuring.setText("按住录音");
        ivAudio.setImageResource(R.drawable.chat_audio_start);
    }

    /**
     * 开始录音
     */
    private void startAudioRecord() {
        if (mRecorder != null && !mRecorder.isRecording())
            try {
                mRecorder.startRecording();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    /**
     * 结束录音
     */
    private void finishAudioRecord() {
        if (mRecorder != null && mRecorder.isRecording())
            try {
                mRecorder.stopRecording();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    /**
     * 播放录音
     */
    private void startPlay() {
        if (voicePlayer == null) {
            voicePlayer = new XtomVoicePlayer(mContext, audioPath);
            voicePlayer.setXtomVoicePlayListener(new VoicePlayListener());
        }

        if (!voicePlayer.isPlaying()) {
            voicePlayer.start();
        }
    }

    /**
     * 停止播放录音
     *
     * @param isRelease
     */
    private void stopPlay(boolean isRelease) {
        if (voicePlayer != null) {
            voicePlayer.stop();
            if (isRelease) {
                voicePlayer.release();
                voicePlayer = null;
            }
        }
    }

    public int getTime() {
        int time = 0;
        if (mRecorder != null)
            time = mRecorder.getTime() / 1000;
        return time;
    }

    private class VoicePlayListener implements XtomVoicePlayListener {

        @Override
        public void loadStart(XtomVoicePlayer player, XtomFileDownLoader loader) {
            // TODO Auto-generated method stub

        }

        @Override
        public void loading(XtomVoicePlayer player, XtomFileDownLoader loader) {
            // TODO Auto-generated method stub

        }

        @Override
        public void loadSuccess(XtomVoicePlayer player,
                                XtomFileDownLoader loader) {
            // TODO Auto-generated method stub

        }

        @Override
        public void loadFailed(XtomVoicePlayer player, XtomFileDownLoader loader) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStart(XtomVoicePlayer player) {
            tvAudioDuring.setText("正在播放");
            ivAudio.setImageResource(R.drawable.chat_audio_play);
            ivDelete.setVisibility(View.INVISIBLE);
            btnSend.setEnabled(false);
        }

        @Override
        public void onPause(XtomVoicePlayer player) {

        }

        @Override
        public void onPlaying(XtomVoicePlayer player) {
            int current = player.getCurrentPosition();
            int s = current / 1000;
        }

        @Override
        public void onStop(XtomVoicePlayer player) {
            tvAudioDuring.setText(audioSecond);
            ivAudio.setImageResource(R.drawable.chat_audio_play);
            ivDelete.setVisibility(View.VISIBLE);
            btnSend.setEnabled(true);
        }

        @Override
        public void onComplete(XtomVoicePlayer player) {
            tvAudioDuring.setText(audioSecond);
            ivAudio.setImageResource(R.drawable.chat_audio_play);
            ivDelete.setVisibility(View.VISIBLE);
            btnSend.setEnabled(true);
        }

        @Override
        public void onError(XtomVoicePlayer player) {
            // TODO Auto-generated method stub

        }

    }

    private Handler recordHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TimeThread.ING:
                    audioPath = mRecorder.getFilePath();
                    recording(msg);
                    break;
                case TimeThread.STOP:
                    ivAudio.setImageResource(R.drawable.chat_audio_play);
                    ivDelete.setVisibility(View.VISIBLE);
                    audioPath = mRecorder.getFilePath();
//				audioSecond = msg.arg1 / 1000+"";
                    audioSecond = getTime() + "";
                    tvAudioDuring.setText(audioSecond);
                    btnSend.setEnabled(true);
                    break;
                default:
                    break;
            }
        }

    };

    /**
     * 录音的方法，正在录音的时候调用此方法
     *
     * @param msg
     */
    private void recording(Message msg) {
        int s = msg.arg1 / 1000;
        if (s >= TOTALSECOND) {
            finishAudioRecord();
            return;
        }
        tvAudioDuring.setText("正在说话");
        int i = (msg.arg1 / 100) % 8;
        //下面是说话过程中的动画
        switch (i / 2) {
            case 0:
                ivAudio.setImageResource(R.drawable.chat_audio_ing_0);
                break;
            case 1:
                ivAudio.setImageResource(R.drawable.chat_audio_ing_1);
                break;
            case 2:
                ivAudio.setImageResource(R.drawable.chat_audio_ing_2);
                break;
            case 3:
                ivAudio.setImageResource(R.drawable.chat_audio_ing_3);
                break;
        }
    }

    private void performTakeVideoRequest() {
        if (hasCameraPermission()) {
            takeVideo();
        } else {
            requestCameraPermission();
        }
        takeVideoPending = true;
    }

    private void takeVideo() {
        final Intent takeVideoIntent = new Intent(
                MediaStore.ACTION_VIDEO_CAPTURE);
        if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
            takeVideoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);//最多30秒
            takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);//画质，0最小，1最大。
            Toast.makeText(this, "最多录制6秒", Toast.LENGTH_SHORT).show();
            startActivityForResult(takeVideoIntent,
                    REQUEST_VIDEO_CAPTURE);
        }
    }

    private boolean hasCameraPermission() {
        int permission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        return permission == PackageManager.PERMISSION_GRANTED;
    }

    private void requestCameraPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                REQUEST_CAMERA_PERMISSION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CAMERA_PERMISSION:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (takePhotoPending) {
//                        takePhoto();
                    } else if (takeVideoPending) {
                        takeVideo();
                    }
                }
                return;
        }
    }

    private void checkVideo(Uri videoUri) {
        if (videoUri == null) {
            Toast.makeText(this, "视频录制失败", Toast.LENGTH_SHORT).show();
            return;
        }
        long duration = MediaUtils.getDuration(getApplicationContext(),
                MediaUtils.getRealVideoPathFromURI(getContentResolver(), videoUri));
        if (duration == 0) {
            duration = MediaUtils
                    .getDuration(getApplicationContext(), videoUri);
        }
        if (duration >= 11000) {//假设限定在6秒，那么这里必须要大于等于6000+1000，不能使用大于6000，因为可能录的视频是60037毫秒的情况，通常会多出几十毫秒。
            Toast.makeText(this, "录制的视频不能超过10秒", Toast.LENGTH_SHORT).show();
            return;
        } else if (duration < 1000) {
            Toast.makeText(this, "录制的视频太短", Toast.LENGTH_SHORT).show();
            return;
        } else {
            String path = uuFileUtils.getFilePathFromContentUri(videoUri, mContext.getContentResolver());
            if (!TextUtils.isEmpty(path)) {
                sendVideo(path);
            } else {
                Toast.makeText(this, "获取视频失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
